/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jpa.controllers;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entity.Courserates;
import entity.User;
import entity.Courses;
import entity.Comments;
import entity.Enrollment;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import jpa.controllers.exceptions.IllegalOrphanException;
import jpa.controllers.exceptions.NonexistentEntityException;

/**
 *
 * @author atap
 */
public class EnrollmentJpaController implements Serializable {

    public EnrollmentJpaController() {
    }
    
    public EnrollmentJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = Persistence.createEntityManagerFactory("EducationXPU");

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Enrollment enrollment) {
        if (enrollment.getCommentsList() == null) {
            enrollment.setCommentsList(new ArrayList<Comments>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Courserates courserates = enrollment.getCourserates();
            if (courserates != null) {
                courserates = em.getReference(courserates.getClass(), courserates.getId());
                enrollment.setCourserates(courserates);
            }
            User userId = enrollment.getUserId();
            if (userId != null) {
                userId = em.getReference(userId.getClass(), userId.getId());
                enrollment.setUserId(userId);
            }
            Courses courseId = enrollment.getCourseId();
            if (courseId != null) {
                courseId = em.getReference(courseId.getClass(), courseId.getCourseId());
                enrollment.setCourseId(courseId);
            }
            List<Comments> attachedCommentsList = new ArrayList<Comments>();
            for (Comments commentsListCommentsToAttach : enrollment.getCommentsList()) {
                commentsListCommentsToAttach = em.getReference(commentsListCommentsToAttach.getClass(), commentsListCommentsToAttach.getId());
                attachedCommentsList.add(commentsListCommentsToAttach);
            }
            enrollment.setCommentsList(attachedCommentsList);
            em.persist(enrollment);
            if (courserates != null) {
                Enrollment oldEnrollmentOfCourserates = courserates.getEnrollment();
                if (oldEnrollmentOfCourserates != null) {
                    oldEnrollmentOfCourserates.setCourserates(null);
                    oldEnrollmentOfCourserates = em.merge(oldEnrollmentOfCourserates);
                }
                courserates.setEnrollment(enrollment);
                courserates = em.merge(courserates);
            }
            if (userId != null) {
                userId.getEnrollmentList().add(enrollment);
                userId = em.merge(userId);
            }
            if (courseId != null) {
                courseId.getEnrollmentList().add(enrollment);
                courseId = em.merge(courseId);
            }
            for (Comments commentsListComments : enrollment.getCommentsList()) {
                Enrollment oldEnrollmentIdOfCommentsListComments = commentsListComments.getEnrollmentId();
                commentsListComments.setEnrollmentId(enrollment);
                commentsListComments = em.merge(commentsListComments);
                if (oldEnrollmentIdOfCommentsListComments != null) {
                    oldEnrollmentIdOfCommentsListComments.getCommentsList().remove(commentsListComments);
                    oldEnrollmentIdOfCommentsListComments = em.merge(oldEnrollmentIdOfCommentsListComments);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }
    
    
    public void edit(Enrollment enrollment) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Enrollment persistentEnrollment = em.find(Enrollment.class, enrollment.getId());
            Courserates courseratesOld = persistentEnrollment.getCourserates();
            Courserates courseratesNew = enrollment.getCourserates();
            User userIdOld = persistentEnrollment.getUserId();
            User userIdNew = enrollment.getUserId();
            Courses courseIdOld = persistentEnrollment.getCourseId();
            Courses courseIdNew = enrollment.getCourseId();
            List<Comments> commentsListOld = persistentEnrollment.getCommentsList();
            List<Comments> commentsListNew = enrollment.getCommentsList();
            List<String> illegalOrphanMessages = null;
            if (courseratesOld != null && !courseratesOld.equals(courseratesNew)) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("You must retain Courserates " + courseratesOld + " since its enrollment field is not nullable.");
            }
            for (Comments commentsListOldComments : commentsListOld) {
                if (!commentsListNew.contains(commentsListOldComments)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Comments " + commentsListOldComments + " since its enrollmentId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (courseratesNew != null) {
                courseratesNew = em.getReference(courseratesNew.getClass(), courseratesNew.getId());
                enrollment.setCourserates(courseratesNew);
            }
            if (userIdNew != null) {
                userIdNew = em.getReference(userIdNew.getClass(), userIdNew.getId());
                enrollment.setUserId(userIdNew);
            }
            if (courseIdNew != null) {
                courseIdNew = em.getReference(courseIdNew.getClass(), courseIdNew.getCourseId());
                enrollment.setCourseId(courseIdNew);
            }
            List<Comments> attachedCommentsListNew = new ArrayList<Comments>();
            for (Comments commentsListNewCommentsToAttach : commentsListNew) {
                commentsListNewCommentsToAttach = em.getReference(commentsListNewCommentsToAttach.getClass(), commentsListNewCommentsToAttach.getId());
                attachedCommentsListNew.add(commentsListNewCommentsToAttach);
            }
            commentsListNew = attachedCommentsListNew;
            enrollment.setCommentsList(commentsListNew);
            enrollment = em.merge(enrollment);
            if (courseratesNew != null && !courseratesNew.equals(courseratesOld)) {
                Enrollment oldEnrollmentOfCourserates = courseratesNew.getEnrollment();
                if (oldEnrollmentOfCourserates != null) {
                    oldEnrollmentOfCourserates.setCourserates(null);
                    oldEnrollmentOfCourserates = em.merge(oldEnrollmentOfCourserates);
                }
                courseratesNew.setEnrollment(enrollment);
                courseratesNew = em.merge(courseratesNew);
            }
            if (userIdOld != null && !userIdOld.equals(userIdNew)) {
                userIdOld.getEnrollmentList().remove(enrollment);
                userIdOld = em.merge(userIdOld);
            }
            if (userIdNew != null && !userIdNew.equals(userIdOld)) {
                userIdNew.getEnrollmentList().add(enrollment);
                userIdNew = em.merge(userIdNew);
            }
            if (courseIdOld != null && !courseIdOld.equals(courseIdNew)) {
                courseIdOld.getEnrollmentList().remove(enrollment);
                courseIdOld = em.merge(courseIdOld);
            }
            if (courseIdNew != null && !courseIdNew.equals(courseIdOld)) {
                courseIdNew.getEnrollmentList().add(enrollment);
                courseIdNew = em.merge(courseIdNew);
            }
            for (Comments commentsListNewComments : commentsListNew) {
                if (!commentsListOld.contains(commentsListNewComments)) {
                    Enrollment oldEnrollmentIdOfCommentsListNewComments = commentsListNewComments.getEnrollmentId();
                    commentsListNewComments.setEnrollmentId(enrollment);
                    commentsListNewComments = em.merge(commentsListNewComments);
                    if (oldEnrollmentIdOfCommentsListNewComments != null && !oldEnrollmentIdOfCommentsListNewComments.equals(enrollment)) {
                        oldEnrollmentIdOfCommentsListNewComments.getCommentsList().remove(commentsListNewComments);
                        oldEnrollmentIdOfCommentsListNewComments = em.merge(oldEnrollmentIdOfCommentsListNewComments);
                    }
                }
            }
            
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = enrollment.getId();
                if (findEnrollment(id) == null) {
                    throw new NonexistentEntityException("The enrollment with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Enrollment enrollment;
            try {
                enrollment = em.getReference(Enrollment.class, id);
                enrollment.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The enrollment with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Courserates courseratesOrphanCheck = enrollment.getCourserates();
            if (courseratesOrphanCheck != null) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Enrollment (" + enrollment + ") cannot be destroyed since the Courserates " + courseratesOrphanCheck + " in its courserates field has a non-nullable enrollment field.");
            }
            List<Comments> commentsListOrphanCheck = enrollment.getCommentsList();
            for (Comments commentsListOrphanCheckComments : commentsListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Enrollment (" + enrollment + ") cannot be destroyed since the Comments " + commentsListOrphanCheckComments + " in its commentsList field has a non-nullable enrollmentId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            User userId = enrollment.getUserId();
            if (userId != null) {
                userId.getEnrollmentList().remove(enrollment);
                userId = em.merge(userId);
            }
            Courses courseId = enrollment.getCourseId();
            if (courseId != null) {
                courseId.getEnrollmentList().remove(enrollment);
                courseId = em.merge(courseId);
            }
            em.remove(enrollment);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Enrollment> findEnrollmentEntities() {
        return findEnrollmentEntities(true, -1, -1);
    }

    public List<Enrollment> findEnrollmentEntities(int maxResults, int firstResult) {
        return findEnrollmentEntities(false, maxResults, firstResult);
    }

    private List<Enrollment> findEnrollmentEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Enrollment.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }
    
    public List<Enrollment> findEnrollmentEntitiesWithUserID(Integer userID) {
        List<Enrollment> enrollmentList = findEnrollmentEntities();
        List<Enrollment> resultList = new ArrayList<Enrollment>();
        
        for (Iterator<Enrollment> it = enrollmentList.iterator(); it.hasNext();) {
            Enrollment enrollment = it.next();
            if (enrollment.getUserId().getId().equals(userID)) {
                resultList.add(enrollment);
            }
        }
        return resultList;
    }
    
        public List<Enrollment> findEnrollmentEntitiesWithCourseID(Integer courseID) {
        List<Enrollment> enrollmentList = findEnrollmentEntities();
        List<Enrollment> resultList = new ArrayList<Enrollment>();
        
        for (Iterator<Enrollment> it = enrollmentList.iterator(); it.hasNext();) {
            Enrollment enrollment = it.next();
            if (enrollment.getCourseId().getCourseId().equals(courseID)) {
                resultList.add(enrollment);
            }
        }
        return resultList;
    }

    public Enrollment findEnrollment(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Enrollment.class, id);
        } finally {
            em.close();
        }
    }
    
    public Enrollment findEnrollment(Integer userID, Integer courseID) {
        List<Enrollment> enrollmentList = findEnrollmentEntities();
        for (Iterator<Enrollment> it = enrollmentList.iterator(); it.hasNext();) {
            Enrollment enrollment = it.next();
            if (enrollment.getUserId().getId().equals(userID) && enrollment.getCourseId().getCourseId().equals(courseID)) {
                return enrollment;
            }
        }
        return null;
    }
    
    public int getEnrollmentCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Enrollment> rt = cq.from(Enrollment.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
